import datetime

from rest_framework.mixins import ListModelMixin
from rest_framework.permissions import IsAuthenticated

from social.rank.models import Rank
from social.rank.serializers import RankSerializer
from social.utils.views import BaseGenericViewSet


class RankViewSet(BaseGenericViewSet, ListModelMixin):
    queryset = Rank.objects.filter()
    serializer_class = RankSerializer
    permission_classes = (IsAuthenticated,)
    pagination_ordering = 'coin'

    def list(self, request, *args, **kwargs):
        rank_type = request.GET.get('rank_type')
        is_income = request.GET.get('is_income') == "true"
        date = datetime.datetime.now()
        if rank_type == 'day':
            key = Rank.key_day_in(date) if is_income else Rank.key_day_out(date)
        elif rank_type == 'week':
            key = Rank.key_week_in(date) if is_income else Rank.key_week_out(date)
        elif rank_type == 'month':
            key = Rank.key_month_in(date) if is_income else Rank.key_month_out(date)

        self.queryset = Rank.objects.select_related('user').filter(key=key).order_by('-coin')
        return super(RankViewSet, self).list(request, *args, **kwargs)
